package com.wzj.yygh.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.util.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;

public class JwtHelper {
    public static final long EXPIRE = 1000*60*60*24;  //24小时过期
    public static final String KEY = "atguigu123";
    public static final String SUBJECT = "YYGH_USER";

     //生成token字符串的方法
    public static String createToken(Long userId,String username){
        return Jwts.builder()
                //JWT头信息
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS2256")
                //设置分类；设置过期时间 一个当前时间，一个加上设置的过期时间常量
                .setSubject(SUBJECT) //主题
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                //设置token主体信息，存储用户信息
                .claim("userId", userId)
                .claim("username", username)
                //.signWith(SignatureAlgorithm.ES256, SECRET)
                .signWith(SignatureAlgorithm.HS256, KEY.getBytes(StandardCharsets.UTF_8))
                .compact();
    }

    // 解析JWT字符串
    public static Claims parseToken(String token) {
        //检查token是否存在
        if (StringUtils.isEmpty(token)) {
            throw new RuntimeException("需要登录");
        }
        //获取解析器
        return Jwts.parser()
                .setSigningKey(KEY.getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token)
                .getBody();
    }

    //通过token获取userId
    public static Long getUserId(String token) {
        Claims claims = parseToken(token);
        if (claims.get("userId") instanceof Integer) {
            Integer userId = (Integer) claims.get("userId");
            return userId.longValue();
        }else {
            return (Long) claims.get("userId");
        }
    }

    public static void main(String[] args) {
        String token = JwtHelper.createToken(1L,"15837664257");
        System.out.println(token);
        System.out.println(getUserId(token));
    }
}
